package com.itheima.springbootwebbtalis.filter;

import com.itheima.springbootwebbtalis.util.JwtUtils;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpStatus;

import java.io.IOException;

@Slf4j
@WebFilter(urlPatterns = "/*")
public class TokenFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        //1.获取请求路径
        System.out.println("uri+"+request.getRequestURI());//String
        System.out.println("url+"+request.getRequestURL());//StringBuilder
        String url = request.getRequestURI().toString();

        //2.判断是否是登录请求（办理门禁卡，直接放行）
        //如果是登录请求，直接放行
        if (url.contains("/login")){
            log.info("登录请求，直接放行");
            filterChain.doFilter(request,response);
            return;//注意：return不能省略
        }

        //3.获取请求头中的令牌（出示令牌）
        String jwt = request.getHeader("token");
        if (jwt == null){
            log.info("请求头中令牌为空，请登录");
            //没有携带令牌（没带门禁机啊，禁止进入小区）封装错误结果
            response.setStatus(HttpStatus.SC_UNAUTHORIZED);
            return;//注意：return不能省略
        }

        //4.解析令牌，判断令牌是否正确（刷门禁卡）
        try {
            JwtUtils.parseJWT(jwt);//依靠工具类解析即可
        } catch (Exception e){
            log.info("令牌解析错误，请重新登录");
            //解析错误（门禁卡失败）封装错误信息
            response.setStatus(HttpStatus.SC_UNAUTHORIZED);
            return;//注意：return不能省略
        }

        //5.放行
        log.info("令牌校验通过，放行");
        filterChain.doFilter(request,response);
    }

}
